package com.je.paas.document.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.core.base.JERequestWrapper;
import com.je.core.exception.PlatformException;
import com.je.core.exception.PlatformExceptionEnum;
import com.je.core.result.BaseRespResult;
import com.je.core.util.*;
import com.je.document.util.JeFileUtil;
import com.je.paas.document.exception.DocumentException;
import com.je.paas.document.model.MetadataEnum;
import com.je.paas.document.model.bean.FileUpload;
import com.je.paas.document.model.bo.FileBO;
import com.je.paas.document.service.DocumentBusService;
import com.je.paas.document.util.MetadataUtil;
import com.je.paas.document.util.Page;
import com.je.paas.document.util.TxtUtil;
import com.je.paas.document.vo.FileVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 文档controller
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/8/27
 */
@Controller("documentControl")
@RequestMapping(value = "/je/document")
public class DocumentController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    //缓存时间
    private static final long Cache_Time = 1000 * 60 * 60 * 24 * 30;
    private static final String[] whiteFileTypes=new String[]{"doc","docx","eml","htm","html","jpg","mht","msg","png","ppt","pptx","rar","txt","xls","xlsx","zip","pdf","jpeg","gif","apk"};

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private DocumentBusService documentBusService;

    @RequestMapping(value = "/getPrivateTempDownloadPath")
    @ResponseBody
    public String getPrivateTempDownloadPath(String bucket,String regionId, String roleArn, String roleSessionName, String filePath, long time) {
        String url = documentBusService.getPrivateTempDownloadPath(bucket,regionId,roleArn,roleSessionName,filePath,time);
        return url;
    }

    /**
     * 上传附件
     * <p>
     * 单附件多附件
     * {'uploadType':'TEMP'}
     * <p>
     * 功能附件
     * {'uploadType':'FUNC','funcCode':'XXXX','tableCode':'XXXXX','pkValue':'YYYYYY'}
     * <p>
     * 附件子功能附件
     * {'uploadType':'SUBFUNC','funcCode':'XXXX','tableCode':'XXXXX','pkValue':'YYYYYY','dicCode':'1','dicId':'1','dicName':'1'}
     * <p>
     * 流程附件
     * {'uploadType':'FLOW','funcCode':'XXXX','tableCode':'XXXXX','pkValue':'YYYYYY'}
     *
     * @param request     请求对象
     * @param metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * @param bucket      存储空间标识
     * @return BaseRespResult
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ResponseBody
    public BaseRespResult file(HttpServletRequest request, String metadataStr, String bucket, String dir) {

        //校验请求是否是附件类型
        if (!(request instanceof MultipartHttpServletRequest)) {
            return BaseRespResult.errorResult(PlatformExceptionEnum.JE_DOC_FILE_READ_ERROR.getCode(), "未找到附件");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        //默认文件上传字段名
        String funcUploadField = "files";
        //获取文件
        List<MultipartFile> files = multipartRequest.getFiles(funcUploadField);

        //校验是否存在文件
        if (files == null || files.isEmpty()) {
            return BaseRespResult.errorResult(PlatformExceptionEnum.JE_DOC_FILE_READ_ERROR.getCode(), "未找到附件");
        }
        //TODO[feature] 增加文件类型限制上传
        if("1".equals(WebUtils.getBackVar("JE_FILE_CHECKTYPE"))) {
            //获取文件
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                if (StringUtil.isNotEmpty(fileName)) {
                    String fileSuffix = JeFileUtil.getInstance().getFileTypeSuffix(fileName);
                    if (StringUtil.isNotEmpty(fileSuffix)) {
                        if (!ArrayUtils.contains(whiteFileTypes, fileSuffix.toLowerCase())) {
                            return BaseRespResult.errorResult(PlatformExceptionEnum.JE_DOC_ERROR.getCode(), "上传文件类型有误!");
                        }
                    }
                }
            }
        }
        //用户ID
        String userId = SecurityUserHolder.getCurrentUser().getUserId();

        //业务元数据添加租户ID
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotEmpty(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }

        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //调用业务方法
        try {
            //保存附件
            List<FileUpload> fileUploadFiles = Lists.newArrayList();
            for (MultipartFile file : files) {
                FileUpload fileUpload = new FileUpload(file.getOriginalFilename(),
                        file.getContentType(), file.getSize(), file.getInputStream());
                fileUploadFiles.add(fileUpload);
            }
            //保存文件并持久化业务数据
            List<FileBO> fileBos = documentBusService.saveFile(fileUploadFiles, userId, metadata, bucket, dir);
            return BaseRespResult.successResult(transformVOList(fileBos));
        } catch (DocumentException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getErrorCode(), e.getCode(), e.getErrorMsg());
        } catch (Exception e) {
            throw new PlatformException("附件上传错误", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
        }
    }


    /**
     * 上传base64数据附件,参数同普通文件上传
     *
     * @param request     请求对象
     * @param metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * @param bucket      存储空间标识
     * @return BaseRespResult
     */
    @RequestMapping(value = "/fileBase64", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult fileBase64(JERequestWrapper request, String metadataStr, String bucket) {

        //默认文件数据字段名
        String funcUploadField = "data";

        //获取文件 示例:
        String base64Str = request.getParameter(funcUploadField);

        //获取文件名
        String fileName = request.getParameter("fileName");
        if (StringUtil.isEmpty(fileName)) {
            fileName = JEUUID.uuid();
        }

        //分隔标识
        String split = "base64,";

        String[] base64StrArray = null;

        //校验是否存在文件
        if (StringUtil.isEmpty(base64Str) || !base64Str.contains(split) || (base64StrArray = base64Str.split(split)).length != 2) {
            return BaseRespResult.errorResult(PlatformExceptionEnum.JE_DOC_FILE_READ_ERROR.getCode(), "未找到附件");
        }

        //文件类型
        String contentType = base64StrArray[0].replaceAll("data:", "").replaceAll(";", "");
        //文件数据
        String base64Data = base64StrArray[1];
        //字符串转byte数组
        byte[] base64ByteArray = Base64.decode(base64Data);
        //byte数组转inputStream
        ByteArrayInputStream inputStream = IoUtil.toStream(base64ByteArray);

        //业务元数据添加租户ID
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotEmpty(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }

        //用户ID
        String userId = SecurityUserHolder.getCurrentUser().getUserId();

        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //调用业务方法
        try {
            //保存附件
            List<FileUpload> fileUploadFiles = Lists.newArrayList();
            //封装文件
            FileUpload fileUpload = new FileUpload(fileName, contentType, (long) inputStream.available(), inputStream);
            fileUploadFiles.add(fileUpload);
            //保存文件并持久化业务数据
            List<FileBO> fileBos = documentBusService.saveFile(fileUploadFiles, userId, metadata, bucket, null);

            return BaseRespResult.successResult(transformVOList(fileBos));
        } catch (DocumentException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getErrorCode(), e.getCode(), e.getErrorMsg());
        } catch (Exception e) {
            throw new PlatformException("附件上传错误", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
        }
    }

    /**
     * 复制文件元数据信息
     *
     * @param request     请求对象
     * @param metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * @param fileKey     文件标志
     * @return BaseRespResult
     */
    @RequestMapping(value = "/copy", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<FileVO> copy(JERequestWrapper request, String metadataStr, String fileKey) {

        //用户ID
        String userId = SecurityUserHolder.getCurrentUser().getUserId();
        //业务元数据添加租户ID
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotEmpty(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }

        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //调用业务方法
        try {
            //获取新名字
            String newRelName = metadata.containsKey("relName") ? metadata.getString("relName") : null;
            //修改元数据
            FileBO fileBO = documentBusService.copyRelByKey(fileKey, newRelName, metadata, userId);
            return BaseRespResult.successResult(transformVO(fileBO));
        } catch (DocumentException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getErrorCode(), e.getCode(), e.getErrorMsg());
        } catch (Exception e) {
            if (e instanceof PlatformException) {
                throw e;
            } else {
                throw new PlatformException("修改失败", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
            }
        }
    }

    /**
     * 更新文件元数据信息
     *
     * @param request     请求对象
     * @param metadataStr 文件业务元数据,JSONObject格式,key范围为 MetadataEnum
     * @param fileKey     文件标志
     * @return BaseRespResult
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<FileVO> update(JERequestWrapper request, String metadataStr, String fileKey) {

        //用户ID
        String userId = SecurityUserHolder.getCurrentUser().getUserId();
        //业务元数据添加租户ID
        JSONObject metadata = new JSONObject();
        if (StringUtils.isNotEmpty(metadataStr)) {
            metadata = JSON.parseObject(metadataStr);
        }
        if (metadata.size() == 0 || StringUtil.isEmpty(fileKey)) {
            throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
        }
        //调用业务方法
        try {
            //获取新名字
            String newRelName = metadata.containsKey("relName") ? metadata.getString("relName") : null;
            //修改元数据
            documentBusService.updateMetadataByKey(fileKey, newRelName, metadata, userId);
            FileBO fileBO = documentBusService.selectFileByKey(fileKey);
            return BaseRespResult.successResult(transformVO(fileBO));
        } catch (Exception e) {
            if (e instanceof PlatformException) {
                throw e;
            } else {
                throw new PlatformException("修改失败", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
            }
        }

    }

    /**
     * 查询附件
     *
     * @param request 请求对象
     * @return BaseRespResult
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<String> select(JERequestWrapper request) {

        //初始化查询对象
        JSONObject metadataQuery = buildMetadataFromRequest(request);
        //调用业务方法
        try {
            //至少包含3个查询条件
            if (metadataQuery.size() < 3) {
                if (metadataQuery.size() < 3) {
                    throw new PlatformException("查询条件至少包含3个！", PlatformExceptionEnum.UNKOWN_ERROR);
                }
            }
            //保存文件并持久化业务数据
            List<FileBO> fileBos = documentBusService.selectFileByMetadata(metadataQuery);
            return BaseRespResult.successResult(transformVOList(fileBos));
        } catch (Exception e) {
            if (e instanceof PlatformException) {
                throw e;
            } else {
                throw new PlatformException("附件查询错误", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
            }
        }
    }

    /**
     * 查询附件分页
     *
     * @param request 请求对象
     * @param start   开始行
     * @param limit   每页行数
     * @param orderBy 排序
     * @return BaseRespResult
     */
    @RequestMapping(value = "/selectPage", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<String> selectPage(JERequestWrapper request, Integer start, Integer limit, String orderBy) {

        //初始化查询对象
        JSONObject metadataQuery = buildMetadataFromRequest(request);

        //调用业务方法
        try {
            //至少包含3个查询条件
            if (metadataQuery.size() < 3) {
                if (metadataQuery.size() < 3) {
                    throw new PlatformException("查询条件至少包含3个！", PlatformExceptionEnum.UNKOWN_ERROR);
                }
            }
            //保存文件并持久化业务数据
            Page<FileBO> fileBOPage = documentBusService.selectFilePageByMetadata(metadataQuery,
                    start == null ? 0 : start, limit == null ? 0 : limit, orderBy);
            return BaseRespResult.successResultPage(transformVOList(fileBOPage.getRows()), fileBOPage.getTotalCount());
        } catch (Exception e) {
            if (e instanceof PlatformException) {
                throw e;
            } else {
                throw new PlatformException("附件查询错误", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
            }
        }
    }

    /**
     * 根据request获取元数据查询对象
     *
     * @param request 请求对象
     * @return com.alibaba.fastjson.JSONObject
     */
    private JSONObject buildMetadataFromRequest(HttpServletRequest request) {

        //初始化查询对象
        JSONObject metadataQuery = new JSONObject();
        //获取所以元数据枚举
        MetadataEnum[] metadataEnums = MetadataEnum.values();
        //添加查询条件
        for (MetadataEnum metadataEnum : metadataEnums) {
            String code = metadataEnum.getCode();
            String value = request.getParameter(code);
            if (StringUtil.isNotEmpty(value)) {
                metadataQuery.put(code, value);
            }
        }
        return metadataQuery;
    }

    /**
     * 文件预览下载
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /preview/{fileKey}
     * /preview?fileKey={fileKey}
     * /down/{fileKey}
     * /down?fileKey={fileKey}
     *
     * @param fileKeyPath  路径参数
     * @param fileKeyParam 请求参数
     */
    @RequestMapping(value = {"/preview/{fileKey}", "/preview", "/down/{fileKey}", "/down"})
    @ResponseBody
    public void previewAndDownload(JERequestWrapper request, HttpServletResponse response,
                                   @PathVariable(name = "fileKey", required = false) String fileKeyPath,
                                   @RequestParam(name = "fileKey", required = false) String fileKeyParam) {
        String version = request.getParameter("version");
        //用户ID
        String userId = SecurityUserHolder.getCurrentUser().getUserId();
        //参数验证
        String fileKey = fileKeyPath;
        if (StringUtils.isEmpty(fileKey)) {
            fileKey = fileKeyParam;
        }
        if (StringUtils.isEmpty(fileKey)) {
            throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
        }
        //请求路径
        String uri = request.getRequestURI();
        try {
            response.reset();
            //获取文件信息
            FileBO fileBO = null;
            if (uri.contains("/preview")) {
                //查询缓存时间
                String modified = request.getHeader("If-Modified-Since");
                if (StringUtils.isNotBlank(modified) && String.valueOf(System.currentTimeMillis()).compareTo(modified) > 0) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
                //获取文件内容
                fileBO = documentBusService.previewFile(fileKey, userId);
                //缓存头，毫秒单位
                response.addHeader("Last-Modified", String.valueOf(System.currentTimeMillis() + Cache_Time));
                response.addHeader("Expires", String.valueOf(System.currentTimeMillis() + Cache_Time));
            } else {
                if (Strings.isNullOrEmpty(version)) {
                    fileBO = documentBusService.downloadFile(fileKey, userId);
                } else {
                    fileBO = documentBusService.downloadFile(fileKey, userId, version);
                }
                String fileName = URLEncoder.encode(fileBO.getRelName(), "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            }
            InputStream is = fileBO.getFile();
            //写入文件流
//            response.setHeader("Content-Length", fileBO.getSize().toString());
            response.setContentType(fileBO.getContentType());
            OutputStream toClient = response.getOutputStream();
            IoUtil.copy(fileBO.getFile(), toClient);
            IoUtil.close(fileBO.getFile());
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            System.out.println("获取文件异常！");
            PlatformException exception;
            if (e instanceof DocumentException) {
                DocumentException e1 = (DocumentException) e;
                exception = new PlatformException(e1.getErrorMsg(), PlatformExceptionEnum.JE_DOC_FILE_UPLOAD_ERROR, e);
            } else {


                exception = new PlatformException(String.format("文件[%s]查找错误", fileKey), PlatformExceptionEnum.UNKOWN_ERROR, request);
            }
            //预览不打印错误
            if (uri.contains("/preview")) {
                logger.error(e.getMessage());
                Writer writer = null;
                try {
                    response.setCharacterEncoding("utf-8");
                    writer = response.getWriter();
                    writer.write(BaseRespResult.errorResult(exception.getCode(), exception.getErrorCode(), exception.getErrorMsg()).toString());
                    writer.flush();
                } catch (IOException io) {
                    logger.error(io.getMessage());
                } finally {
                    IoUtil.close(writer);
                }
            } else {
                throw exception;
            }
        }
    }

    /**
     * 预览文件返回文本
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /previewTxt/{fileKey}
     * /previewTxt?fileKey={fileKey}
     *
     * @param fileKeyPath  路径参数
     * @param fileKeyParam 请求参数
     */
    @RequestMapping(value = {"/previewTxt/{fileKey}", "/previewTxt"}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<String> previewTxt(JERequestWrapper request, HttpServletResponse response,
                                             @PathVariable(name = "fileKey", required = false) String fileKeyPath,
                                             @RequestParam(name = "fileKey", required = false) String fileKeyParam) {

        try {
            //用户ID
            String userId = SecurityUserHolder.getCurrentUser().getUserId();
            //参数验证
            String fileKey = fileKeyPath;
            if (StringUtils.isEmpty(fileKey)) {
                fileKey = fileKeyParam;
            }
            if (StringUtils.isEmpty(fileKey)) {
                throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
            }

            //文件对象
            FileBO fileBO = documentBusService.previewFile(fileKey, userId);

            //读取文本内容
            String content = TxtUtil.inputStream2String(fileBO.getFile());
            IoUtil.close(fileBO.getFile());

            return BaseRespResult.successResult(content);
        } catch (PlatformException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlatformException("文本内容获取失败!", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
        }

    }

    /**
     * 获取文件缩略图 仅支持图片
     * <p>
     * 优先级: 路径参数 > 请求参数
     * 请求方式:
     * /thumbnail/{fileKey}
     * /thumbnail?fileKey={fileKey}
     *
     * @param fileKeyPath  路径参数
     * @param fileKeyParam 请求参数
     */
    @RequestMapping(value = {"/thumbnail/{fileKey}", "/thumbnail"})
    @ResponseBody
    public void thumbnail(JERequestWrapper request, HttpServletResponse response,
                          @PathVariable(name = "fileKey", required = false) String fileKeyPath,
                          @RequestParam(name = "fileKey", required = false) String fileKeyParam) {

        try {
            //参数验证
            String fileKey = fileKeyPath;
            if (StringUtils.isEmpty(fileKey)) {
                fileKey = fileKeyParam;
            }
            if (StringUtils.isEmpty(fileKey)) {
                throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
            }
            //查询缓存时间
            String modified = request.getHeader("If-Modified-Since");
            if (StringUtils.isNotBlank(modified) && String.valueOf(System.currentTimeMillis()).compareTo(modified) > 0) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
            //缓存头，毫秒单位
            response.addHeader("Last-Modified", String.valueOf(System.currentTimeMillis() + Cache_Time));
            response.addHeader("Expires", String.valueOf(System.currentTimeMillis() + Cache_Time));

            InputStream inputStream = documentBusService.thumbnail(fileKey);
            if (inputStream == null) {
                throw new PlatformException("未保存缩略图", PlatformExceptionEnum.UNKOWN_ERROR, request);
            }
            //写入文件流
            response.setContentType("image/png");
            OutputStream toClient = response.getOutputStream();
            IoUtil.copy(inputStream, toClient);
            IoUtil.close(inputStream);
            toClient.flush();
            toClient.close();
        } catch (PlatformException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlatformException("缩略图获取失败", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
        }

    }

    /**
     * 文件打包下载
     * <p>
     * 请求方式:
     * /downZip?fileKeys={fileKeys}
     *
     * @param fileKeys 文件唯一标识集合;json数组格式字符串
     * @param zipName  压缩包名称，为空时使用当前时间戳
     */
    @RequestMapping(value = "/downZip")
    @ResponseBody
    public void downZip(HttpServletResponse response, String fileKeys, String zipName) {

        try {
            if (StringUtils.isEmpty(fileKeys)) {
                throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
            }
            //base64转码
            fileKeys = Base64.decodeStr(fileKeys);
            //fileKeys转换list
            List<String> fileKeyList = JSON.parseArray(fileKeys, String.class);
            InputStream zipInputStream = documentBusService.buildZip(fileKeyList);
            response.reset();
            String fileName = URLEncoder.encode(StringUtils.isNotEmpty(zipName) ? zipName : System.currentTimeMillis() + ".zip", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Content-Length", String.valueOf(zipInputStream.available()));
            //写入文件流
            response.setContentType("application/zip");
            OutputStream toClient = response.getOutputStream();
            IoUtil.copy(zipInputStream, toClient);
            IoUtil.close(zipInputStream);
            toClient.flush();
            toClient.close();
        } catch (PlatformException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlatformException("打包下载失败", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
        }

    }

    /**
     * 获取文件属性
     *
     * @param fileKey 文件唯一标识
     * @return com.je.core.result.<com.je.paas.document.vo.FileAttributesVO>
     */
    @RequestMapping(value = "/attributes", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<FileVO> attributes(String fileKey) {
        if (StringUtils.isEmpty(fileKey)) {
            throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
        }
        try {
            //初始化返回参数
            FileVO vo = transformVO(documentBusService.selectFileByKey(fileKey));
            return BaseRespResult.successResult(vo);
        } catch (Exception e) {
            if (e instanceof PlatformException) {
                throw e;
            } else {
                throw new PlatformException("文件信息查找错误", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
            }
        }
    }

    /**
     * 删除附件
     *
     * @param fileKeys 附件唯一标识
     * @return com.je.core.result.BaseRespResult<java.lang.String>
     */
    @RequestMapping(value = "/del", produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<String> del(String fileKeys) {
        if (StringUtils.isEmpty(fileKeys)) {
            throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
        }
        try {
            //用户ID
            String userId = SecurityUserHolder.getCurrentUser().getUserId();
            //删除
            documentBusService.delFilesByKey(Arrays.asList(fileKeys.split(ArrayUtils.SPLIT)), userId);
            return BaseRespResult.successResult("成功");
        } catch (Exception e) {
            if (e instanceof PlatformException) {
                throw e;
            } else {
                throw new PlatformException("文件信息查找错误", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
            }
        }

    }

    /**
     * BO转VO
     *
     * @param fileBos BO集合
     * @return java.util.List<com.je.paas.document.vo.FileVO>
     */
    private List<FileVO> transformVOList(List<FileBO> fileBos) {
        //构建VO
        List<FileVO> fileVOS = new ArrayList<>();
        for (FileBO fileBO : fileBos) {
            fileVOS.add(transformVO(fileBO));
        }
        return fileVOS;
    }

    /**
     * BO转VO
     *
     * @param fileBO BO实体
     * @return java.util.List<com.je.paas.document.vo.FileVO>
     */
    private FileVO transformVO(FileBO fileBO) {

        FileVO vo = new FileVO();
        vo.setFileKey(fileBO.getFileKey());
        vo.setRelName(fileBO.getRelName());
        vo.setFullUrl(fileBO.getFullUrl());
        vo.setSuffix(fileBO.getSuffix());
        vo.setHasThumbnail(StringUtil.isNotEmpty(fileBO.getThumbnail()));
        vo.setSize(fileBO.getSize());
        vo.setCreateTime(fileBO.getCreateTime());
        vo.setDicCode(fileBO.getDicCode());
        vo.setDicId(fileBO.getDicId());
        vo.setDicName(fileBO.getDicName());
        vo.setRemarks(fileBO.getRemarks());
        vo.setCreateUserDeptName(fileBO.getCreateUserDeptName());
        vo.setCreateUserName(fileBO.getCreateUserName());
        return vo;
    }

}
